package com.junlong0716.enjoylearning.ui

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.ClipboardManager
import android.text.TextUtils
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.junlong0716.enjoylearning.CommentPresenter
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.CommentAdapter
import com.junlong0716.enjoylearning.entity.CommentEntity
import com.junlong0716.enjoylearning.service.RecordStudyEndService
import com.junlong0716.enjoylearning.widget.CustomActionWebView
import com.junlong0716.enjoylearning.widget.listener.ActionSelectListener
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_web.*
import kotlinx.android.synthetic.main.view_title_bar.*

class WebActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var webSettings: WebSettings
    private lateinit var webChromeClient: WebChromeClient
    private lateinit var txWebView: CustomActionWebView
    private lateinit var commentData: java.util.ArrayList<CommentEntity.DataBean.ListBean>
    private var webUrl = ""
    private var webTitle = ""
    private var webId = 0
    private lateinit var commentAdapter: CommentAdapter
    private lateinit var commentPresenter: CommentPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web)
        webUrl = intent.getStringExtra("document_url")
        webId = intent.getIntExtra("document_id", 0)
        webTitle = intent.getStringExtra("document_title")
        commentPresenter = CommentPresenter()
        initView()
        initListener()
        rl_right.visibility = View.VISIBLE

        commentPresenter.requestKnowledgeDetail(webId, object : CommentPresenter.RequestKnowledgeDetailCallback {
            override fun requestKnowledgeDetailsSucceed(knowledgeTitle: String, knowledgeContent: String, createDate: Long, browseNum: Int, isCollect: Int, praise: Int, praiseNum: Int, coverImg: String, author: String, knowledgeDescribe: String, fileAddress: String) {
                if (isCollect == 0) {

                } else if (isCollect == 1) {
                    tv_collection.text = "已收藏"
                    fl_collection.isClickable = false
                }

                if (praise == 1) {
                    tpv.setBackgroundResource(R.mipmap.ic_love_sel)
                    rl_like.isClickable = false
                    tv_like.text = praiseNum.toString()
                }
            }
        })


        rl_right.setOnClickListener {
            val intent = Intent(this, ContactActivity::class.java)
            intent.putExtra("KNOWLEDGE_ID", webId)
            startActivity(intent)
        }

//        commentPresenter.requestKnowledgeDetail(webId, object : CommentPresenter.RequestKnowledgeDetailCallback {
//            override fun requestKnowledgeDetailsSucceed(knowledgeTitle: String, knowledgeContent: String, createDate: Long, browseNum: Int, isCollect: Int, isPraise: Int, praiseNum: Int, coverImg: String, author: String, knowledgeDescribe: String) {
//                if (isPraise == 1) {
//                    tpv.setBackgroundResource(R.mipmap.ic_love_sel)
//                    rl_like.isClickable = false
//                    tv_like.text = praiseNum.toString()
//                }
//            }
//        })


    }

    override fun onResume() {
        super.onResume()

        commentPresenter.requestAddStudyTime(this, webId, object : CommentPresenter.AddStudyTimeCallback {
            override fun requestAddStudyTimeSucceed() {
                Logger.d("----------记录时间成功----------")
            }

            override fun requestAddStudyTimeFailed() {
                Logger.d("----------记录时间失败----------")
            }
        })

    }

    private fun initListener() {
        fl_conform.setOnClickListener(this)
        fl_collection.setOnClickListener(this)
        rl_like.setOnClickListener(this)
    }

    private fun initView() {
        rl_back.setOnClickListener { finish() }
        tv_title.text = webTitle
        commentData = ArrayList()
        rv_comment.layoutManager = LinearLayoutManager(this)
        commentAdapter = CommentAdapter(commentData, R.layout.item_comment)
        rv_comment.adapter = commentAdapter

        val emptyView = LayoutInflater.from(this@WebActivity).inflate(R.layout.view_empty, null)
        emptyView.findViewById<TextView>(R.id.tv_empty_content).text = "还没有人评论呢~ 快来抢沙发吧！"
        commentAdapter.emptyView = emptyView

        //动态添加webview 防止内存泄露
        txWebView = CustomActionWebView(this)
        val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)
        txWebView.layoutParams = layoutParams
        commentAdapter.addHeaderView(txWebView)
        commentAdapter.setHeaderAndEmpty(true)
        //ll_container.addView(txWebView, 1)
        initWebView()
        txWebView.loadUrl("http://123.127.109.109:8091/knowledge-show.html?k=${webId}")


        commentAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ll_love_container -> {
                    val commentPresenter = CommentPresenter()
                    commentPresenter.requestAddCommentPraise(commentData[position].id, this, object : CommentPresenter.AddCommentPraiseCallback {
                        override fun requestAddCommentPraiseSucceed() {
                            requestCommentData()
                        }

                        override fun requestAddCommentPraiseFailed() {
                            ToastUtils.showShort("评论失败！")
                        }
                    })
                }

                R.id.tv_delete -> {
                    val commentPresenter = CommentPresenter()
                    commentPresenter.requestDelMyComment(this, commentData[position].id, object : CommentPresenter.DelMyCommentCallback {
                        override fun requestDelMyCommentFailed() {
                            ToastUtils.showShort("删除失败！")
                        }

                        override fun requestDelMyCommentSucceed() {
                            ToastUtils.showShort("删除成功！")
                            requestCommentData()
                        }
                    })
                }
            }
        }


    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        txWebView.isDrawingCacheEnabled = true
        webChromeClient = WebChromeClient()
        txWebView.webChromeClient = webChromeClient
        //txWebView.webViewClient = CustomWebViewClient()
        webSettings = txWebView.settings

        // 修改ua使得web端正确判断(加标识+++++++++++++++++++++++++++++++++++++++++++++++++++++)
//        String ua = webSettings.getUserAgentString();
//        webSettings.setUserAgentString(ua + "这里是增加的标识");

        // 网页内容的宽度是否可大于WebView控件的宽度
        webSettings.loadWithOverviewMode = false
        // 保存表单数据
        webSettings.saveFormData = true
        webSettings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK //关闭webview中缓存
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        webSettings.setSupportZoom(false)

        webSettings.builtInZoomControls = true
        //隐藏原生的缩放控件
        webSettings.displayZoomControls = false

        txWebView.requestFocus() //此句可使html表单可以接收键盘输入
        txWebView.isFocusable = true
        webSettings.useWideViewPort = true
        webSettings.savePassword = true
        webSettings.setGeolocationEnabled(true)
        webSettings.domStorageEnabled = true
        webSettings.javaScriptEnabled = true
        // 启动应用缓存
        webSettings.setAppCacheEnabled(false)
        // 设置缓存模式
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        // 设置此属性，可任意比例缩放。
        webSettings.useWideViewPort = false
        webSettings.setSupportZoom(false) //支持缩放，默认为true。是下面那个的前提。
        webSettings.builtInZoomControls = false //设置内置的缩放控件。若为false，则该WebView不可缩放
        //  页面加载好以后，再放开图片
        webSettings.blockNetworkImage = false
        // 使用localStorage则必须打开
        webSettings.domStorageEnabled = true
        // 排版适应屏幕
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        // WebView是否支持多个窗口。
        webSettings.setSupportMultipleWindows(true)
        webSettings.useWideViewPort = true // 关键点
        webSettings.allowFileAccess = true // 允许访问文件
        //将图片调整到适合webview的大小
        webSettings.useWideViewPort = true
        // webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//        }
        // 缩放至屏幕的大小
        webSettings.loadWithOverviewMode = true
        //其他细节操作
        webSettings.allowFileAccess = true //设置可以访问文件
        webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
        webSettings.loadsImagesAutomatically = true //支持自动加载图片
        webSettings.defaultTextEncodingName = "utf-8"//设置编码格式
        webSettings.domStorageEnabled = true//JS在HTML里面设置了本地存储localStorage，java中使用localStorage则必须打开
        txWebView.settings.domStorageEnabled = true
        txWebView.settings.useWideViewPort = true //自适应屏幕

        //以下接口禁止(直接或反射)调用，避免视频画面无法显示：
        //webView.setLayerType();
        txWebView.isDrawingCacheEnabled = true

        //去除QQ浏览器推广广告
        window.decorView.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
            val outView = ArrayList<View>()
            window.decorView.findViewsWithText(outView, "QQ浏览器", View.FIND_VIEWS_WITH_TEXT)
            if (outView.size > 0) {
                outView[0].visibility = View.GONE
            }
        }
        txWebView.webViewClient = object : WebViewClient() {

            override fun shouldOverrideUrlLoading(webView: WebView, s: String): Boolean {
                webView.loadUrl(s)
                return true
            }

            override fun onPageFinished(p0: WebView?, p1: String?) {
                super.onPageFinished(p0, p1)
                requestCommentData()
            }
        }

        txWebView.setOnKeyListener { view, i, keyEvent ->
            if (keyEvent.action == KeyEvent.ACTION_DOWN) {
                if (i == KeyEvent.KEYCODE_BACK && txWebView.canGoBack()) {
                    txWebView.goBack()
                    return@setOnKeyListener true  //已处理
                }
            }
            return@setOnKeyListener false
        }


        val list = java.util.ArrayList<String>()
        list.add("记笔记")
        list.add("复制")
        //设置item
        txWebView.setActionList(list)

        //链接js注入接口，使能选中返回数据
        txWebView.linkJSInterface()

        txWebView.settings.builtInZoomControls = true
        txWebView.settings.displayZoomControls = false
        //使用javascript
        txWebView.settings.javaScriptEnabled = true
        txWebView.settings.domStorageEnabled = true

        //增加点击回调
        txWebView.setActionSelectListener({ title, selectText ->
            when (title) {
                "记笔记" -> {
                    val intent = Intent(this@WebActivity, AddNoteActivity::class.java)
                    intent.putExtra("WEB_ID", webId)
                    intent.putExtra("SELECT_TEXT", selectText)
                    intent.putExtra("IS_UPDATE_NOTE", false)
                    startActivity(intent)
                    overridePendingTransition(R.anim.anim_up, R.anim.anim_down)
                }
                "复制" -> {
                    // 从API11开始android推荐使用android.content.ClipboardManager
                    // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
                    val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    // 将文本内容放到系统剪贴板里。
                    cm.text = selectText
                    ToastUtils.showShort("复制成功！")
                }
            }
        })
    }


    private fun requestCommentData() {


        val commentPresenter = CommentPresenter()
        commentPresenter.requestComment(this, 1, 20, webId, object : CommentPresenter.RequestCommentCallback {
            override fun requestCommentSucceed(commentData: ArrayList<CommentEntity.DataBean.ListBean>) {
                if (commentData.isEmpty()) {
                    this@WebActivity.commentData.clear()
                } else {
                    this@WebActivity.commentData.clear()
                    this@WebActivity.commentData.addAll(commentData)
                }
                commentAdapter.notifyDataSetChanged()
            }
        })
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.fl_conform -> {
                val commentVal = edt_comment.text.toString().trim()
                val commentPresenter = CommentPresenter()
                if (!TextUtils.isEmpty(commentVal)) {
                    commentPresenter.requestAddComment(this, MyApp.instance().userAccount!!.id, webId, commentVal, object : CommentPresenter.RequestAddCommentCallback {
                        override fun requestAddCommentSucceed() {
                            requestCommentData()
                            ToastUtils.showShort("评论成功！")
                            edt_comment.setText("")
                            if (KeyboardUtils.isSoftInputVisible(this@WebActivity)) {
                                KeyboardUtils.hideSoftInput(this@WebActivity)
                            }
                        }
                    })
                } else {
                    ToastUtils.showShort("请填写评论内容！")
                }
            }

            R.id.fl_collection -> {
                val commentPresenter = CommentPresenter()

                if (tv_collection.text.toString() == "已收藏") {

                } else if (tv_collection.text.toString() == "收藏") {
                    commentPresenter.requestAddCollection(this, MyApp.instance().userAccount!!.id, webId, object : CommentPresenter.RequestAddCollectionCallback {
                        override fun requestAddCollectionSucceed() {
                            tv_collection.text = "已收藏"
                            fl_collection.isClickable = false
                            ToastUtils.showShort("收藏成功！")
                        }
                    })
                }
            }

            R.id.rl_like -> {
                val commentPresenter = CommentPresenter()
                commentPresenter.requestAddPraise(webId, object : CommentPresenter.AddPraiseCallback {
                    override fun requestAddPraiseSucceed() {
                        tpv.setBackgroundResource(R.mipmap.ic_love_sel)
                        tv_like.text = (tv_like.text.toString().toInt() + 1).toString()
                        rl_like.isClickable = false
                    }
                })
            }

            else -> {

            }
        }
    }

    override fun onPause() {
        super.onPause()
        val intent = Intent(this, RecordStudyEndService::class.java)
        intent.putExtra("KNOWLEDGE_ID", webId)
        startService(intent)
    }
}
